<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
hello world!
<button id="btn">发送消息</button>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script th:inline="javascript">
    $(function () {
        let index;

        if (typeof (WebSocket) != "undefined") {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于
            let name = "xiaomi" + Math.round(Math.random() * 10000);
            let url = "http://localhost:8080/upload/imgs/20210629/1624937372011_623.jpg"
            index = new WebSocket("ws://localhost:8080/websocket/oneToMany?name=" + name + "&url=" + url);
            //socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
            //打开事件
            index.onopen = function () {
                console.log("Socket 已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            index.onmessage = function (msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            index.onclose = function () {
                console.log("Socket已关闭");
            };
            //发生了错误事件
            index.onerror = function () {
                alert("Socket发生了错误");
                //此时可以尝试刷新页面
            }
            //离开页面时，关闭socket
            //jquery1.8中已经被废弃，3.0中已经移除
            // $(window).unload(function(){
            //     socket.close();
            //});
        } else {
            console.log("您的浏览器不支持WebSocket");
        }

        $("#btn").click(function () {
            index.send("你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好," +
                "你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好," +
                "你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好," +
                "你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好,");
        })
    })

</script>

</html>
